<template>
  <div class="order-page">
    <!-- 顶部导航 -->
    <van-nav-bar title="我的订单" left-arrow @click-left="goBack" />

    <!-- 订单状态标签页 -->
    <van-tabs v-model="activeTab" @change="onTabChange" sticky>
      <van-tab>
        <template #title>
          全部
          <van-badge v-if="orderCounts.total > 0" :content="orderCounts.total" />
        </template>
      </van-tab>
      <van-tab>
        <template #title>
          待支付
          <van-badge v-if="orderCounts.pending > 0" :content="orderCounts.pending" />
        </template>
      </van-tab>
      <van-tab>
        <template #title>
          待服务
          <van-badge v-if="orderCounts.processing > 0" :content="orderCounts.processing" />
        </template>
      </van-tab>
      <van-tab>
        <template #title>
          已完成
          <van-badge v-if="orderCounts.completed > 0" :content="orderCounts.completed" />
        </template>
      </van-tab>
      <van-tab>
        <template #title>
          已取消
          <van-badge v-if="orderCounts.cancelled > 0" :content="orderCounts.cancelled" />
        </template>
      </van-tab>
    </van-tabs>

    <!-- 加载状态 -->
    <van-loading v-if="loading" type="spinner" color="#1989fa" vertical>
      加载中...
    </van-loading>

    <!-- 订单列表 -->
    <div v-else-if="filteredOrders.length > 0" class="order-list">
      <div v-for="order in filteredOrders" :key="order.orderId || order.orderid" class="order-card">
        <!-- 订单头部 -->
        <div class="order-header">
          <div class="order-info">
            <span class="order-id">订单号：{{ order.orderId || order.orderid }}</span>
            <van-tag :type="getOrderStatusType(order.status)" size="medium">
              {{ getOrderStatusText(order.status) }}
            </van-tag>
          </div>
          <div class="order-time">{{ formatDateTime(order.createtime || order.createTime) }}</div>
        </div>

        <!-- 订单内容 -->
        <div class="order-content">
          <div class="service-info">
            <div class="service-title">{{ order.itemType || '服务项目' }}</div>
            <div class="service-details">
              <div class="repair-types">维修类型：{{ getRepairTypes(order.repairTypes) }}</div>
              <div class="service-time">预约时间：{{ formatDateTime(order.serviceTime) }}</div>
              <div class="service-address">服务地址：{{ order.address }}</div>
            </div>
          </div>

          <!-- 需求描述 -->
          <div v-if="order.demandDescription" class="demand-description">
            <div class="description-title">需求描述：</div>
            <div class="description-content">{{ order.demandDescription }}</div>
          </div>

          <!-- 图片预览 -->
          <div v-if="order.pictures && getPictures(order.pictures).length > 0" class="pictures-container">
            <div class="pictures-title">问题图片：</div>
            <div class="pictures-grid">
              <div 
                v-for="(pic, index) in getPictures(order.pictures)" 
                :key="index" 
                class="picture-item"
                @click="previewImage(pic, getPictures(order.pictures))"
              >
                <van-image 
                  :src="pic" 
                  fit="cover" 
                  :show-error="true"
                  :show-loading="true"
                  error-icon="photo-fail"
                  loading-icon="photo"
                />
              </div>
            </div>
            <div class="pictures-count">共 {{ getPictures(order.pictures).length }} 张图片</div>
          </div>
        </div>

        <!-- 订单底部操作 -->
        <div class="order-footer">
          <div class="price-info">
            <div v-if="order.status === 2" class="service-completion">
              <van-icon name="success" color="#07c160" size="16" />
              <span class="completion-text">服务已完成</span>
            </div>
            <div class="service-info-text">服务ID：{{ order.serviceId || order.serviceid }}</div>
          </div>
          <div class="order-actions">
            <!-- 待支付状态 -->
            <template v-if="order.status === 0">
              <van-button size="small" @click="handleCancel(order)">取消订单</van-button>
              <van-button size="small" type="primary" @click="handlePay(order)">立即支付</van-button>
            </template>
            
            <!-- 待服务状态 -->
            <template v-if="order.status === 1">
              <van-button size="small" @click="handleContact(order)">联系师傅</van-button>
            </template>
            
            <!-- 已完成状态 -->
            <template v-if="order.status === 2">
              <!-- 只有未评价的订单才显示"去评价"按钮 -->
              <van-button 
                v-if="!order.hasEvaluation"
                size="small" 
                type="warning"
                @click="handleEvaluate(order)"
              >
                <van-icon name="star-o" size="14" />
                去评价
              </van-button>
              <!-- 已评价显示提示 -->
              <van-tag v-else type="success" size="medium">
                <van-icon name="success" size="12" />
                已评价
              </van-tag>
              <van-button 
                size="small" 
                plain
                type="primary"
                @click="handleReorder(order)"
              >
                <van-icon name="replay" size="14" />
                再次下单
              </van-button>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <van-empty v-else :description="emptyDescription" image="search">
      <template v-if="orders.length === 0">
        <van-button round type="primary" @click="goToHome" class="empty-button">
          去下单
        </van-button>
      </template>
    </van-empty>

    <!-- 底部导航 -->
    <van-tabbar v-model="activeTabbar" @change="onTabbarChange" class="bottom-tabbar">
      <van-tabbar-item icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item icon="apps-o">分类</van-tabbar-item>
      <van-tabbar-item icon="orders-o">订单</van-tabbar-item>
      <van-tabbar-item icon="user-o">我的</van-tabbar-item>
    </van-tabbar>

    <!-- 评价弹窗 -->
    <van-popup
      :show="showEvaluationForm"
      @update:show="showEvaluationForm = $event"
      position="bottom"
      :style="{ height: '80%' }"
      round
      closeable
      @close="closeEvaluationForm"
    >
      <div class="evaluation-dialog">
        <div class="dialog-header">
          <h3>服务评价</h3>
          <van-button size="small" type="primary" @click="saveEvaluation">
            发布评价
          </van-button>
        </div>

        <div class="dialog-content">
          <!-- 订单信息 -->
          <div class="order-info" v-if="currentEvaluationOrder">
            <div class="order-item">
              <span class="label">订单号：</span>
              <span class="value">{{ currentEvaluationOrder.orderid || currentEvaluationOrder.orderId }}</span>
            </div>
            <div class="order-item">
              <span class="label">服务类型：</span>
              <span class="value">{{ currentEvaluationOrder.itemType }} - {{ getRepairTypes(currentEvaluationOrder.repairTypes) }}</span>
            </div>
          </div>

          <!-- 评价表单 -->
          <div class="form-section">
            <van-field
              v-model="evaluationData.title"
              label="评价标题"
              placeholder="请输入评价标题"
              required
            />

            <van-field
              v-model="evaluationData.content"
              label="评价内容"
              type="textarea"
              placeholder="请详细描述您的服务体验..."
              rows="4"
              maxlength="500"
              show-word-limit
              required
            />

            <!-- 服务评分 -->
            <div class="rating-section">
              <div class="rating-label">服务评分</div>
              <van-rate 
                v-model="evaluationData.rating" 
                :size="24" 
                color="#ff6b35"
                void-color="#eee"
                allow-half
              />
              <span class="rating-text">{{ getRatingText(evaluationData.rating) }}</span>
            </div>

            <!-- 图片上传 -->
            <div class="upload-section">
              <div class="upload-label">体验图片（可选）</div>
              <ImageUploader v-model="evaluationData.image" />
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { getOrders, publishReview, pushView, uploadImageApi, checkOrderEvaluation, deleteOrder } from '@/api/index.js';
import { showToast, showSuccessToast, showFailToast, showConfirmDialog, showImagePreview, showLoadingToast, closeToast } from 'vant';
import ImageUploader from '@/components/ImageUploader.vue';
import { useUserStore } from '@/stores/user.js';

const router = useRouter();
const userStore = useUserStore();

// 状态管理
const activeTab = ref(0);
const activeTabbar = ref(2);
const loading = ref(false);
const orders = ref([]);

// 评价相关状态
const showEvaluationForm = ref(false);
const currentEvaluationOrder = ref(null);

// 评价表单数据
const evaluationData = reactive({
  title: '',
  content: '',
  rating: 5,
  image: '',
  orderid: '',
  serviceid: '',
  userid: ''
});

// 计算属性：统计各状态订单数量
const orderCounts = computed(() => {
  return {
    total: orders.value.length,
    pending: orders.value.filter(o => o.status === 0).length,      // 待支付
    processing: orders.value.filter(o => o.status === 1).length,   // 待服务
    completed: orders.value.filter(o => o.status === 2).length,    // 已完成
    cancelled: orders.value.filter(o => o.status === 3).length,    // 已取消
  };
});

// 计算属性：根据标签页过滤订单
const filteredOrders = computed(() => {
  console.log('========== 订单过滤逻辑 ==========');
  console.log('当前标签页索引:', activeTab.value);
  console.log('订单总数:', orders.value.length);
  
  if (activeTab.value === 0) {
    // 全部订单
    console.log('显示全部订单');
    return orders.value;
  } else {
    // 根据标签页索引映射到订单状态
    // 标签页: 0-全部, 1-待支付, 2-待服务, 3-已完成, 4-已取消
    // 订单状态: 0-待支付, 1-待服务, 2-已完成, 3-已取消
    const statusMap = {
      1: 0, // 标签页1(待支付) -> 订单状态0
      2: 1, // 标签页2(待服务) -> 订单状态1  
      3: 2, // 标签页3(已完成) -> 订单状态2
      4: 3, // 标签页4(已取消) -> 订单状态3
    };
    
    const targetStatus = statusMap[activeTab.value];
    console.log('目标状态:', targetStatus);
    
    if (targetStatus !== undefined) {
      const filtered = orders.value.filter(order => order.status === targetStatus);
      console.log(`过滤结果: 状态${targetStatus}的订单有${filtered.length}条`);
      console.log('过滤后的订单:', filtered);
      return filtered;
    } else {
      console.warn('未知的标签页索引:', activeTab.value);
      return [];
    }
  }
});

// 计算属性：空状态描述
const emptyDescription = computed(() => {
  const tabNames = ['订单', '待支付订单', '待服务订单', '已完成订单', '已取消订单'];
  const currentTabName = tabNames[activeTab.value] || '订单';
  
  if (orders.value.length === 0) {
    return '暂无订单数据，快去下单吧~';
  } else {
    return `暂无${currentTabName}`;
  }
});

// 返回上一页
const goBack = () => {
  router.back();
};

// 标签页切换
const onTabChange = (index) => {
  console.log('========== 标签页切换 ==========');
  console.log('切换到标签页索引：', index);
  
  // 标签页名称映射
  const tabNames = ['全部', '待支付', '待服务', '已完成', '已取消'];
  const currentTabName = tabNames[index] || '全部';
  
  // 统计当前标签页的订单数量
  const currentCount = filteredOrders.value.length;
  
  console.log(`当前标签页：【${currentTabName}】`);
  console.log(`过滤后的订单数量：${currentCount} 条`);
  console.log('过滤后的订单详情：', filteredOrders.value);
  
  // 验证过滤结果
  if (index > 0) {
    const expectedStatus = index - 1; // 标签页1对应状态0，标签页2对应状态1，以此类推
    const actualStatuses = filteredOrders.value.map(order => order.status);
    const allMatch = actualStatuses.every(status => status === expectedStatus);
    console.log(`✅ 过滤验证: 期望状态=${expectedStatus}, 实际状态=[${actualStatuses.join(',')}], 匹配=${allMatch}`);
    
    // 显示过滤后的订单详情
    filteredOrders.value.forEach((order, idx) => {
      console.log(`  订单${idx + 1}: ID=${order.orderId || order.orderid}, 状态=${order.status}(${getOrderStatusText(order.status)}), 类型=${order.itemType}`);
    });
  }
  
  // 如果当前标签页没有订单，给出提示
  if (currentCount === 0 && orders.value.length > 0) {
    showToast({
      message: `暂无${currentTabName}订单`,
      duration: 1500,
    });
  }
  
  console.log('================================');
};

// 底部导航切换
const onTabbarChange = (index) => {
  console.log('切换到底部导航：', index);
  switch (index) {
    case 0:
      router.push({ name: 'home' });
      break;
    case 1:
      router.push({ name: 'category' });
      break;
    case 2:
      // 当前页面，不需要跳转
      break;
    case 3:
      router.push({ name: 'center' });
      break;
  }
};

// 获取订单状态类型（用于标签颜色）
const getOrderStatusType = (status) => {
  const statusMap = {
    0: 'warning',   // 待支付
    1: 'primary',   // 已支付/待服务
    2: 'success',   // 已完成
    3: 'default',   // 已取消
    4: 'danger',    // 退款中
    5: 'info',      // 售后中
  };
  return statusMap[status] || 'default';
};

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '待服务',
    2: '已完成',
    3: '已取消',
    4: '退款中',
    5: '售后中',
  };
  return statusMap[status] || '未知状态';
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取维修类型文本
const getRepairTypes = (repairTypes) => {
  if (!repairTypes) return '-';
  try {
    const types = JSON.parse(repairTypes);
    return Array.isArray(types) ? types.join('、') : repairTypes;
  } catch (e) {
    return repairTypes;
  }
};

// 获取图片数组
const getPictures = (pictures) => {
  if (!pictures) return [];
  
  try {
    // 如果是JSON数组格式，解析JSON
    if (typeof pictures === 'string' && pictures.trim().startsWith('[') && pictures.trim().endsWith(']')) {
      const parsedPictures = JSON.parse(pictures);
      if (Array.isArray(parsedPictures)) {
        return parsedPictures.filter(pic => pic && pic.trim());
      }
    }
    
    // 如果是逗号分隔的字符串格式（向后兼容）
    if (typeof pictures === 'string' && pictures.includes(',')) {
      return pictures.split(',').filter(pic => pic && pic.trim());
    }
    
    // 如果是单个图片URL字符串
    if (typeof pictures === 'string' && pictures.trim()) {
      return [pictures.trim()];
    }
    
    // 如果已经是数组
    if (Array.isArray(pictures)) {
      return pictures.filter(pic => pic && pic.trim());
    }
    
    return [];
  } catch (error) {
    console.error('解析图片数据失败:', error, '原始数据:', pictures);
    // 解析失败时，尝试作为逗号分隔的字符串处理
    if (typeof pictures === 'string') {
      return pictures.split(',').filter(pic => pic && pic.trim());
    }
    return [];
  }
};

// 预览图片
const previewImage = (current, images) => {
  showImagePreview({
    images: images,
    startPosition: images.indexOf(current),
    closeable: true,
  });
};

// 加载订单数据
const loadOrders = async () => {
  try {
    loading.value = true;
    
    // 获取当前用户ID
    const currentUserId = userStore.id;
    if (!currentUserId) {
      showFailToast({
        message: '请先登录',
        duration: 2000,
      });
      loading.value = false;
      return;
    }
    
    console.log('当前用户ID：', currentUserId);
    const response = await getOrders(currentUserId);
    console.log('订单数据加载结果：', response);
    
    if (response && response.code === 200) {
      // 统一字段命名，保留原始订单状态
      const orderList = (response.data || []).map(order => ({
        ...order,
        // 后端返回orderId，统一使用orderId作为主字段
        orderId: order.orderId || order.orderid,
        serviceId: order.serviceId || order.serviceid, 
        userId: order.userId || order.userid,
        status: order.status !== undefined ? order.status : 2, // 保留原始状态，默认为已完成
        // 为了兼容性，也保留小写字段
        orderid: order.orderId || order.orderid,
        serviceid: order.serviceId || order.serviceid,
        userid: order.userId || order.userid,
        // 初始化评价状态
        hasEvaluation: false
      }));
      
      // 检查每个订单是否已评价
      await checkOrdersEvaluation(orderList);
      
      orders.value = orderList;
      console.log('========== 订单加载完成 ==========');
      console.log('订单总数：', orders.value.length);
      console.log('订单数据（含评价状态）：', orders.value);
      
      // 调试图片数据
      orders.value.forEach((order, index) => {
        if (order.pictures) {
          console.log(`订单${index + 1} 图片数据:`, {
            原始数据: order.pictures,
            数据类型: typeof order.pictures,
            解析结果: getPictures(order.pictures)
          });
        }
      });
      
      if (orders.value.length > 0) {
        // 统计各状态订单数量
        const statusCount = {
          0: orders.value.filter(o => o.status === 0).length, // 待支付
          1: orders.value.filter(o => o.status === 1).length, // 待服务
          2: orders.value.filter(o => o.status === 2).length, // 已完成
          3: orders.value.filter(o => o.status === 3).length, // 已取消
        };
        const evaluatedCount = orders.value.filter(o => o.hasEvaluation).length;
        
        console.log('订单状态统计：', statusCount);
        console.log('各状态订单详情：');
        console.log('  - 待支付(status=0):', orders.value.filter(o => o.status === 0));
        console.log('  - 待服务(status=1):', orders.value.filter(o => o.status === 1));
        console.log('  - 已完成(status=2):', orders.value.filter(o => o.status === 2));
        console.log('  - 已取消(status=3):', orders.value.filter(o => o.status === 3));
        console.log('已评价订单数：', evaluatedCount);
        console.log('================================');
        
        showSuccessToast({
          message: `加载成功！共 ${orders.value.length} 条订单\n待支付${statusCount[0]}·待服务${statusCount[1]}·已完成${statusCount[2]}·已取消${statusCount[3]}`,
          duration: 2500,
        });
      }
    } else {
      const errorMsg = response?.message || '加载订单失败';
      showFailToast({
        message: errorMsg,
        duration: 2000,
      });
    }
  } catch (error) {
    console.error('加载订单异常:', error);
    showFailToast({
      message: '网络异常，请稍后重试',
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 检查订单是否已评价
const checkOrdersEvaluation = async (orderList) => {
  try {
    // 并发检查所有订单的评价状态
    const checkPromises = orderList.map(async (order) => {
      try {
        const orderId = order.orderId || order.orderid;
        const response = await checkOrderEvaluation(orderId);
        if (response && response.code === 200) {
          order.hasEvaluation = response.data === true || response.data?.hasEvaluation === true;
        }
      } catch (error) {
        console.warn(`检查订单 ${order.orderId || order.orderid} 评价状态失败:`, error);
        // 检查失败时默认为未评价
        order.hasEvaluation = false;
      }
    });
    
    await Promise.all(checkPromises);
  } catch (error) {
    console.error('批量检查订单评价状态异常:', error);
  }
};

// 支付订单
const handlePay = (order) => {
  console.log('支付订单：', order);
  showToast('跳转到支付页面...');
};

// 联系师傅
const handleContact = (order) => {
  console.log('联系师傅：', order);
  showToast('师傅正在赶来的路上，请稍等...');
};

// 去评价
const handleEvaluate = (order) => {
  console.log('去评价按钮被点击，订单数据：', order);
  console.log('点击前 showEvaluationForm.value:', showEvaluationForm.value);
  
  // 设置当前评价订单
  currentEvaluationOrder.value = order;
  
  // 重置评价表单数据
  resetEvaluationForm();
  
  // 设置订单相关字段到评价表单
  evaluationData.orderid = order.orderId || order.orderid;
  evaluationData.serviceid = order.serviceId || order.serviceid;
  evaluationData.userid = order.userId || order.userid;
  console.log('订单相关字段已设置到评价表单：', evaluationData.userid );
  
  // 不需要设置userid，后端会从订单中自动获取
  console.log('设置评价表单数据:', evaluationData.userid);
  
  // 显示评价表单
  showEvaluationForm.value = true;
  
  console.log('点击后 showEvaluationForm.value:', showEvaluationForm.value);
  console.log('currentEvaluationOrder.value:', currentEvaluationOrder.value);
  console.log('evaluationData:', evaluationData);
  
  // 强制触发响应式更新
  setTimeout(() => {
    console.log('延时检查 showEvaluationForm.value:', showEvaluationForm.value);
  }, 100);
};

// 重置评价表单
const resetEvaluationForm = () => {
  evaluationData.title = '';
  evaluationData.content = '';
  evaluationData.rating = 5;
  evaluationData.image = '';
  evaluationData.orderid = '';
  evaluationData.serviceid = '';
  evaluationData.userid = '';
};

// 关闭评价表单
const closeEvaluationForm = () => {
  showEvaluationForm.value = false;
  resetEvaluationForm();
};

// 评价成功回调
const handleEvaluationSuccess = (evaluationData) => {
  console.log('评价成功:', evaluationData);
  showSuccessToast({
    message: '评价已发布，感谢您的反馈！',
    duration: 2000
  });
  
  // 重新加载订单数据
  loadOrders();
};

// 取消订单
const handleCancel = async (order) => {
  console.log('取消订单：', order);
  
  const orderId = order.orderId || order.orderid;
  if (!orderId) {
    showFailToast('订单ID不存在，无法取消订单');
    return;
  }
  
  try {
    await showConfirmDialog({
      title: '取消订单',
      message: `确定要取消订单 ${orderId} 吗？\n取消后将无法恢复。`,
      confirmButtonText: '确定取消',
      cancelButtonText: '我再想想',
      confirmButtonColor: '#ee0a24',
    });
    
    // 用户确认取消订单
    console.log('开始调用取消订单API，订单ID:', orderId);
    
    showLoadingToast({
      message: '正在取消订单...',
      forbidClick: true,
    });
    
    // 调用删除订单API
    const response = await deleteOrder(orderId);
    console.log('取消订单API响应:', response);
    
    closeToast();
    
    if (response && response.code === 200) {
      showSuccessToast({
        message: '订单取消成功！',
        duration: 2000,
      });
      
      // 重新加载订单列表
      await loadOrders();
      
      console.log('订单取消成功，已刷新订单列表');
    } else {
      const errorMsg = response?.message || '取消订单失败';
      showFailToast({
        message: errorMsg,
        duration: 2500,
      });
      console.error('取消订单失败:', errorMsg);
    }
  } catch (error) {
    closeToast();
    
    if (error === 'cancel') {
      // 用户取消了确认对话框
      console.log('用户取消了订单取消操作');
      return;
    }
    
    console.error('取消订单异常:', error);
    showFailToast({
      message: '网络异常，请稍后重试',
      duration: 2500,
    });
  }
};

// 去首页下单
const goToHome = () => {
  router.push({ name: 'home' });
};

// 获取评分文本
const getRatingText = (rating) => {
  if (rating >= 4.5) return '非常满意';
  if (rating >= 4) return '满意';
  if (rating >= 3) return '一般';
  if (rating >= 2) return '不满意';
  return '很不满意';
};

// 上传图片到服务器
const uploadImage = async (imageData) => {
  if (!imageData) return null;
  
  try {
    // 如果是base64格式，需要转换为File对象
    let file;
    if (typeof imageData === 'string' && imageData.startsWith('data:image/')) {
      // 将base64转换为blob
      const response = await fetch(imageData);
      const blob = await response.blob();
      file = new File([blob], 'evaluation-image.jpg', { type: 'image/jpeg' });
    } else if (imageData instanceof File) {
      file = imageData;
    } else {
      console.warn('不支持的图片格式:', typeof imageData);
      return null;
    }

    // 创建FormData
    const formData = new FormData();
    formData.append('image', file);

    console.log('开始上传图片:', file.name, file.size);
    
    // 调用上传API
    const uploadResponse = await uploadImageApi(formData);
    console.log('图片上传结果:', uploadResponse);

    if (uploadResponse && uploadResponse.code === 200 && uploadResponse.data && uploadResponse.data.url) {
      console.log('图片上传成功，URL:', uploadResponse.data.url);
      return uploadResponse.data.url; // 返回图片URL
    } else {
      console.error('图片上传失败:', uploadResponse?.message);
      return null;
    }
  } catch (error) {
    console.error('图片上传异常:', error);
    return null;
  }
};

// 保存评价
const saveEvaluation = async () => {
  // 表单验证
  if (!evaluationData.orderid) {
    showFailToast('订单信息缺失');
    return;
  }

  if (!evaluationData.title.trim()) {
    showFailToast('请输入评价标题');
    return;
  }

  if (!evaluationData.content.trim()) {
    showFailToast('请输入评价内容');
    return;
  }

  try {
    showLoadingToast({
      message: '发布评价中...',
      forbidClick: true,
    });

    // 先上传图片（如果有的话）
    let imageUrl = null;
    if (evaluationData.image) {
      console.log('检测到图片，开始上传:', evaluationData.image);
      showLoadingToast({
        message: '正在上传图片...',
        forbidClick: true,
      });
      
      imageUrl = await uploadImage(evaluationData.image);
      if (evaluationData.image && !imageUrl) {
        closeToast();
        showFailToast('图片上传失败，请重试');
        return;
      }
      
      console.log('图片上传完成，URL:', imageUrl);
    }

    showLoadingToast({
      message: '正在提交评价...',
      forbidClick: true,
    });

    // 准备提交数据 - 只发送后端需要的字段
    const reviewData = {
      orderid: evaluationData.orderid,
      serviceid: evaluationData.serviceid,
      // 不需要传递userid，后端会从订单中自动获取
      score: evaluationData.rating,
      content: `${evaluationData.title.trim()}: ${evaluationData.content.trim()}`,
      city: currentEvaluationOrder.value?.address ? currentEvaluationOrder.value.address.split(' ')[0] : '未知城市',
      imageUrl: typeof imageUrl === 'string' ? imageUrl : null // 确保是字符串或null，不是对象
    };

    console.log('提交评价数据:', reviewData);
    console.log('图片URL详细信息:', {
      原始imageUrl: imageUrl,
      类型检查: typeof imageUrl,
      最终imageUrl: reviewData.imageUrl
    });
    console.log('当前订单数据:', currentEvaluationOrder.value);
    console.log('订单ID检查:', {
      orderid: currentEvaluationOrder.value.orderid,
      orderId: currentEvaluationOrder.value.orderId,
      final: reviewData.orderid
    });

    // 调用API - 使用pushView方法发布到首页展示
    const response = await pushView(reviewData);
    console.log('评价提交结果:', response);

    closeToast();

    if (response && response.code === 200) {
      showSuccessToast({
        message: '🌟 评价发布成功！感谢您的反馈',
        duration: 2500
      });
      
      // 关闭弹窗
      closeEvaluationForm();
      
      // 通知成功
      handleEvaluationSuccess(reviewData);
    } else {
      const errorMsg = response?.message || '评价发布失败';
      showFailToast({
        message: errorMsg,
        duration: 2500
      });
    }
  } catch (error) {
    console.error('评价提交异常:', error);
    closeToast();
    showFailToast({
      message: '网络异常，请稍后重试',
      duration: 2500
    });
  }
};

// 再次下单
const handleReorder = (order) => {
  console.log('再次下单：', order);
  
  showConfirmDialog({
    title: '再次下单',
    message: `确定要为 ${order.itemType} 再次下单吗？\n将使用相同的服务地址和需求描述。`,
    confirmButtonText: '确定下单',
    cancelButtonText: '取消',
  }).then(() => {
    // 用户确认再次下单
    showSuccessToast({
      message: '🎉 订单已提交，师傅将尽快联系您！',
      duration: 2500,
    });
    
    // 这里可以跳转到下单页面并预填信息
    // router.push({ 
    //   name: 'order', 
    //   query: { 
    //     itemType: order.itemType,
    //     address: order.address,
    //     description: order.demandDescription
    //   }
    // });
  }).catch(() => {
    // 用户取消
  });
};

// 页面加载时获取订单数据
onMounted(() => {
  loadOrders();
});
</script>

<style lang="scss" scoped>
.order-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 50px;
}

.order-list {
  padding: 8px;
}

.order-card {
  background: white;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-id {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-content {
  padding: 16px;
}

.service-info {
  margin-bottom: 12px;
}

.service-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.service-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.repair-types,
.service-time,
.service-address {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.demand-description {
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #1989fa;
}

.description-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.description-content {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.pictures-container {
  margin-bottom: 12px;
}

.pictures-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.pictures-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 8px;
  max-width: 300px;
}

.pictures-count {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: right;
}

.picture-item {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  
  .van-image {
    width: 100%;
    height: 100%;
  }
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.service-completion {
  display: flex;
  align-items: center;
  gap: 4px;
}

.completion-text {
  font-size: 14px;
  color: #07c160;
  font-weight: 500;
}

.service-info-text {
  font-size: 12px;
  color: #999;
}

.order-actions {
  display: flex;
  gap: 8px;
  
  .van-button {
    display: flex;
    align-items: center;
    gap: 4px;
    font-weight: 500;
    
    &--warning {
      background: linear-gradient(135deg, #ff9500 0%, #ff7700 100%);
      border: none;
      
      &:hover {
        background: linear-gradient(135deg, #ff7700 0%, #ff5500 100%);
      }
    }
    
    &--primary.van-button--plain {
      border-color: #1989fa;
      color: #1989fa;
      
      &:hover {
        background: rgba(25, 137, 250, 0.1);
      }
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  color: #999;
  margin-bottom: 20px;
}

.bottom-button {
  width: 160px;
  margin-top: 16px;
}

.empty-button {
  margin-top: 20px;
  padding: 0 40px;
}

/* 底部导航样式 */
.bottom-tabbar {
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

/* 标签页徽章样式 */
:deep(.van-tab__text) {
  display: flex;
  align-items: center;
  gap: 4px;
  
  .van-badge {
    position: relative;
    top: -2px;
    
    .van-badge__wrapper {
      background: #ff4444;
      border-radius: 10px;
      padding: 0 6px;
      min-width: 18px;
      height: 18px;
      line-height: 18px;
      font-size: 11px;
      font-weight: 600;
    }
  }
}

/* 激活标签页的徽章样式 */
:deep(.van-tab--active) {
  .van-badge__wrapper {
    background: #1989fa;
  }
}

/* 评价弹窗样式 */
.evaluation-dialog {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
  
  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
}

.dialog-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
}

/* 订单信息 */
.order-info {
  background: #fff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 16px;
  border: 1px solid #e8e8e8;
}

.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 14px;

  &:last-child {
    margin-bottom: 0;
  }
}

.order-item .label {
  color: #666;
  min-width: 80px;
  flex-shrink: 0;
}

.order-item .value {
  color: #333;
  flex: 1;
  font-weight: 500;
}

/* 表单区域 */
.form-section {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  
  .van-field {
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

/* 评分区域 */
.rating-section {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}

.rating-label {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.rating-text {
  margin-left: 12px;
  font-size: 14px;
  color: #ff6b35;
  font-weight: 500;
}

/* 上传区域 */
.upload-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.upload-label {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-card {
    padding: 12px;
    margin-bottom: 8px;
  }
  
  .order-header {
    padding: 10px 12px;
  }
  
  .order-content {
    padding: 12px;
  }
  
  .order-footer {
    padding: 10px 12px;
  }
  
  .service-title {
    font-size: 15px;
  }
  
  .pictures-grid {
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  }
  
  .picture-item {
    width: 60px;
    height: 60px;
  }
}
</style>
